

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/hello_lixi.gitee.io/img/fluid.png">
  <link rel="icon" href="/hello_lixi.gitee.io/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Mr.LI">
  <meta name="keywords" content="">
  
    <meta name="description" content="前后端分离项目出现跨域问题">
<meta property="og:type" content="article">
<meta property="og:title" content="跨域处理问题">
<meta property="og:url" content="https://xistudycode.gitee.io/hello_lixi.gitee.io/2023/04/10/%E8%B7%A8%E5%9F%9F%E5%A4%84%E7%90%86/index.html">
<meta property="og:site_name" content="Welcome to the technology blog">
<meta property="og:description" content="前后端分离项目出现跨域问题">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20230410174118926.png">
<meta property="og:image" content="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20230411105517051.png">
<meta property="article:published_time" content="2023-04-10T09:38:19.092Z">
<meta property="article:modified_time" content="2023-04-17T05:47:34.940Z">
<meta property="article:author" content="Mr.LI">
<meta property="article:tag" content="跨域">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20230410174118926.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>跨域处理问题 - Welcome to the technology blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/hello_lixi.gitee.io/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/hello_lixi.gitee.io/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/hello_lixi.gitee.io/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"xistudycode.gitee.io","root":"/hello_lixi.gitee.io/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/hello_lixi.gitee.io/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/hello_lixi.gitee.io/js/utils.js" ></script>
  <script  src="/hello_lixi.gitee.io/js/color-schema.js" ></script>
  

  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/hello_lixi.gitee.io/">
      <strong>xBlog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hello_lixi.gitee.io/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/hello_lixi.gitee.io/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="跨域处理问题"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        Mr.LI
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-04-10 17:38" pubdate>
          2023年4月10日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          7.6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          64 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">跨域处理问题</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年4月17日 下午
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h3 id="跨域问题的原因"><a href="#跨域问题的原因" class="headerlink" title="跨域问题的原因"></a>跨域问题的原因</h3><p>在现在流行的前后端分离开发中，跨域问题突显了出来，跨域问题的根本原因：浏览器有同源策略限制，当前域名的js只能读取同域下的窗口属性，这是一个基础安全功能。那么什么是同源策略呢？即两资源的URL中 协议，域名，端口，都相同则称为同源，若两资源为不同源，则不允许共享资源。</p>
<p>例如：以 <a target="_blank" rel="noopener" href="http://www.baidu.com/dir1/a.html">http://www.baidu.com/dir1/a.html</a> 为例子</p>
<p><img src="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20230410174118926.png" srcset="/hello_lixi.gitee.io/img/loading.gif" lazyload alt="image-20230410174118926"></p>
<p><strong>注： 核心判断方式为，端口及端口左边的地址要完全一致</strong></p>
<h3 id="CORS"><a href="#CORS" class="headerlink" title="CORS"></a>CORS</h3><p>  CORS是Cross-Origin Resource Sharing的缩写。也就是支持跨域资源共享，即不同域之间可以进行资源的相互访问。那么为什么要有CORS呢，其实很简单，浏览器的同源政策保证了安全的同时，也让我们不能访问其它域的资源，即使开发者认为的安全操作也不行，这时，我们就可以用一套协议来告诉浏览器，这某几个域在我们的服务范围之内，不要一棍打死。即有如下改变：<br>CORS出现之前：<br>  浏览器接收到服务器回复 –&gt; 检查是否同源 –&gt; 不同源就拒绝响应！/同源就响应！<br>CORS出现之后：<br>  浏览器接收到服务器回复 –&gt; 检查一下response header –&gt; 发现有特定字段Access-Control-Allow-Origin –&gt; 检查这个header后面的值包不包含自己所在的域（打比方我们现在在<a target="_blank" rel="noopener" href="http://www.baidu.com),浏览器检查发现后response/">www.baidu.com)，浏览器检查发现后response</a> header里面写的有Access-Control-Allow-Origin: <a target="_blank" rel="noopener" href="https://www.baidu.com,https//www.google.com">https://www.baidu.com，https://www.google.com</a> 。正好我们在允许的域里面！ –&gt; 浏览器响应服务器返回的数据(response)。</p>
<h3 id="CORS-实现逻辑"><a href="#CORS-实现逻辑" class="headerlink" title="CORS 实现逻辑"></a>CORS 实现逻辑</h3><p>  CORS需要浏览器和服务器也就是B/S两端分别实现！</p>
<p>浏览器要实现的内容：<br>  接收到服务器的回复之后检测回复头里面是否含有特定字段！有的话查看自己的域名是否在内，一定要这两个条件都符合！浏览器才会接受（或者说响应）服务器返回的回复！</p>
<p>服务器需要实现的内容：<br>  服务器需要在接受到浏览器发来的请求（request）后，在返回response之前！设置header，在header中里面包含特定字段，以便浏览器收到回复之后可以去检查，有字段证明服务器同意服务这个网站，浏览器就可以接受回复，没有字段或者字段的值不包含发送请求的网站，浏览器就不会响应回复内容！</p>
<h3 id="跨域问题的解决方案"><a href="#跨域问题的解决方案" class="headerlink" title="跨域问题的解决方案"></a>跨域问题的解决方案</h3><ul>
<li><p>修改浏览器的设置 （不推荐，不安全）</p>
</li>
<li><p>修改请求的方式：jsonp （不推荐，诸多限制）</p>
</li>
<li><p>用 Nignx 统一访问域</p>
</li>
<li><p>CORS 前端后端代码实现</p>
</li>
</ul>
<h4 id="CORS的后端代码实现"><a href="#CORS的后端代码实现" class="headerlink" title="CORS的后端代码实现"></a>CORS的后端代码实现</h4><p>1.在Controller上加上@CrossOrigin 注解或者@CrossOrigin(origins = “ <a target="_blank" rel="noopener" href="http://localhost:8081/">http://localhost:8081</a> ”)。优点是粒度更细，某URL是否跨域可以分开配置，缺点是，如果整个项目都要跨域，则每个controller都需要添加注解</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RestController</span><br><span class="hljs-comment">//解决跨域问题</span><br><span class="hljs-meta">@CrossOrigin(origins = &quot;*&quot;,allowCredentials=&quot;true&quot;,allowedHeaders = &quot;*&quot;,methods = &#123;POST,GET&#125;)</span><br><span class="hljs-meta">@RequestMapping(&quot;/staff&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">StaffController</span> &#123;<br>    <span class="hljs-meta">@Resource</span><br>    StaffServiceImp staffServiceImp;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure>



<p>2.创建配置类CorsConfig，此方法统一配置，用的较多</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CorsConfig</span> &#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">MAX_AGE</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;18000L&quot;</span>;<br> <br> <span class="hljs-comment">//跨域处理</span><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> WebFilter <span class="hljs-title function_">corsFilter</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> (ServerWebExchange ctx, WebFilterChain chain) -&gt; &#123;<br>            <span class="hljs-type">ServerHttpRequest</span> <span class="hljs-variable">request</span> <span class="hljs-operator">=</span> ctx.getRequest();<br>            <br>        	<span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">remoteAddr</span> <span class="hljs-operator">=</span> getIpAddr(request);<br>            <span class="hljs-type">HttpHeaders</span> <span class="hljs-variable">requestHeaders</span> <span class="hljs-operator">=</span> request.getHeaders();<br>            request.mutate().headers(httpHeaders-&gt;&#123;<br>            	httpHeaders.add(GlobalConstants.CLIENT_IP, remoteAddr);<br>            	httpHeaders.add(GlobalConstants.XCMG_FEIGN_HEADER, GlobalConstants.XCMG_FEIGN_HEADER_VALUE);<br>                <span class="hljs-type">String</span> <span class="hljs-variable">token</span> <span class="hljs-operator">=</span> requestHeaders.getFirst(<span class="hljs-string">&quot;Authorization&quot;</span>);<br>                <span class="hljs-keyword">if</span> (token != <span class="hljs-literal">null</span>) &#123;<br>                    httpHeaders.add(GlobalConstants.XCMG_TOKEN, requestHeaders.getFirst(<span class="hljs-string">&quot;authorization&quot;</span>));<br>                    httpHeaders.add(GlobalConstants.USER_ID, JWTUtil.getUserId(token));<br>                    httpHeaders.add(GlobalConstants.USER_NAME, JWTUtil.getUserName(token));<br>                &#125;<br>            &#125;);<br>            <span class="hljs-keyword">if</span> (CorsUtils.isCorsRequest(request)) &#123;<br>                <span class="hljs-type">ServerHttpResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> ctx.getResponse();<br>                <span class="hljs-type">HttpMethod</span> <span class="hljs-variable">requestMethod</span> <span class="hljs-operator">=</span> requestHeaders.getAccessControlRequestMethod();<br>                <span class="hljs-type">HttpHeaders</span> <span class="hljs-variable">headers</span> <span class="hljs-operator">=</span> response.getHeaders();<br>                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());<br>                headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders<br>                        .getAccessControlRequestHeaders());<br>                <span class="hljs-keyword">if</span>(requestMethod != <span class="hljs-literal">null</span>)&#123;<br>                	headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, <span class="hljs-string">&quot;&quot;</span>);<br>                &#125;<br>                headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, <span class="hljs-string">&quot;true&quot;</span>);<br>                headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, <span class="hljs-string">&quot;*&quot;</span>);<br>                headers.remove(HttpHeaders.ALLOW);<br>                headers.remove(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS);<br>                headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);<br>                <span class="hljs-keyword">if</span> (request.getMethod() == HttpMethod.OPTIONS) &#123;<br>                    response.setStatusCode(HttpStatus.OK);<br>                    <span class="hljs-keyword">return</span> Mono.empty();<br>                &#125;<br> <br>            &#125;<br>            <span class="hljs-keyword">return</span> chain.filter(ctx);<br>        &#125;;<br>    &#125;<br> <br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> ServerCodecConfigurer <span class="hljs-title function_">serverCodecConfigurer</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">DefaultServerCodecConfigurer</span>();<br>    &#125;<br> <br>&#125;<br></code></pre></td></tr></table></figure>



<p>或者</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CorsConfig</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">WebMvcConfigurer</span> &#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">addCorsMappings</span><span class="hljs-params">(CorsRegistry registry)</span> &#123;<br>        registry.addMapping(<span class="hljs-string">&quot;/**&quot;</span>)<br>                .allowedOrigins(<span class="hljs-string">&quot;*&quot;</span>)<br>                .allowedMethods(<span class="hljs-string">&quot;GET&quot;</span>, <span class="hljs-string">&quot;HEAD&quot;</span>, <span class="hljs-string">&quot;POST&quot;</span>, <span class="hljs-string">&quot;PUT&quot;</span>, <span class="hljs-string">&quot;DELETE&quot;</span>, <span class="hljs-string">&quot;OPTIONS&quot;</span>)<br>                .allowCredentials(<span class="hljs-literal">true</span>)<br>                .maxAge(<span class="hljs-number">3600</span>)<br>                .allowedHeaders(<span class="hljs-string">&quot;*&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>若是出现如下问题</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs pgsql">java.lang.IllegalArgumentException: <span class="hljs-keyword">When</span> allowCredentials <span class="hljs-keyword">is</span> <span class="hljs-keyword">true</span>, allowedOrigins cannot contain the special <span class="hljs-keyword">value</span> &quot;*&quot;since that cannot be <span class="hljs-keyword">set</span> <span class="hljs-keyword">on</span> the &quot;Access-Control-Allow-Origin&quot; response <span class="hljs-keyword">header</span>. <span class="hljs-keyword">To</span> allow credentials <span class="hljs-keyword">to</span> a <span class="hljs-keyword">set</span> <span class="hljs-keyword">of</span> origins, list them explicitly <span class="hljs-keyword">or</span> consider <span class="hljs-keyword">using</span> &quot;allowedOriginPatterns&quot; <span class="hljs-keyword">instead</span>.<br></code></pre></td></tr></table></figure>

<p>则是因为SpringBoot升级2.4.0之后，跨域配置中的<code>.allowedOrigins</code>不再可用，将配置中的<code>.allowedOrigins</code>替换成<code>.allowedOriginPatterns</code>即可。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java">SpringBoot2<span class="hljs-number">.0</span><span class="hljs-number">.0</span>中<br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CorsConfig</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">WebMvcConfigurer</span> &#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">addCorsMappings</span><span class="hljs-params">(CorsRegistry registry)</span> &#123;<br>        registry.addMapping(<span class="hljs-string">&quot;/**&quot;</span>).allowedOrigins(<span class="hljs-string">&quot;*&quot;</span>)<br>                .allowedMethods(<span class="hljs-string">&quot;GET&quot;</span>, <span class="hljs-string">&quot;HEAD&quot;</span>, <span class="hljs-string">&quot;POST&quot;</span>,<span class="hljs-string">&quot;PUT&quot;</span>, <span class="hljs-string">&quot;DELETE&quot;</span>, <span class="hljs-string">&quot;OPTIONS&quot;</span>)<br>                .allowCredentials(<span class="hljs-literal">true</span>).maxAge(<span class="hljs-number">3600</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>SpringBoot2.4.0中（亲测可用，实验设备管理项目中使用)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CorsConfig</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">WebMvcConfigurer</span> &#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">addCorsMappings</span><span class="hljs-params">(CorsRegistry registry)</span> &#123;<br>        registry.addMapping(<span class="hljs-string">&quot;/**&quot;</span>).allowedOriginPatterns(<span class="hljs-string">&quot;*&quot;</span>)<br>                .allowedMethods(<span class="hljs-string">&quot;GET&quot;</span>, <span class="hljs-string">&quot;HEAD&quot;</span>, <span class="hljs-string">&quot;POST&quot;</span>,<span class="hljs-string">&quot;PUT&quot;</span>, <span class="hljs-string">&quot;DELETE&quot;</span>, <span class="hljs-string">&quot;OPTIONS&quot;</span>)<br>                .allowCredentials(<span class="hljs-literal">true</span>).maxAge(<span class="hljs-number">3600</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>







<p>3.创建一个过滤器CorsFilter</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@WebFilter(filterName = &quot;CorsFilter &quot;)</span><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CorsFilter</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Filter</span> &#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">doFilter</span><span class="hljs-params">(ServletRequest req, ServletResponse res, FilterChain chain)</span> <span class="hljs-keyword">throws</span> IOException, ServletException &#123;<br>        <br>        <span class="hljs-type">HttpServletResponse</span> <span class="hljs-variable">response</span> <span class="hljs-operator">=</span> (HttpServletResponse) res;<br>        response.setHeader(<span class="hljs-string">&quot;Access-Control-Allow-Origin&quot;</span>,<span class="hljs-string">&quot;*&quot;</span>);<br>        response.setHeader(<span class="hljs-string">&quot;Access-Control-Allow-Credentials&quot;</span>, <span class="hljs-string">&quot;true&quot;</span>);<br>        response.setHeader(<span class="hljs-string">&quot;Access-Control-Allow-Methods&quot;</span>, <span class="hljs-string">&quot;POST, GET, PATCH, DELETE, PUT&quot;</span>);<br>        response.setHeader(<span class="hljs-string">&quot;Access-Control-Max-Age&quot;</span>, <span class="hljs-string">&quot;3600&quot;</span>);<br>        response.setHeader(<span class="hljs-string">&quot;Access-Control-Allow-Headers&quot;</span>, <span class="hljs-string">&quot;Origin, X-Requested-With, Content-Type, Accept&quot;</span>);<br>        <br>        <span class="hljs-type">HttpServletRequest</span> <span class="hljs-variable">httpRequest</span> <span class="hljs-operator">=</span> (HttpServletRequest) req;<br>		<span class="hljs-comment">// OPTIONS method response</span><br>		<span class="hljs-keyword">if</span> (httpRequest.getMethod().equals(<span class="hljs-string">&quot;OPTIONS&quot;</span>))<br>			((HttpServletResponse) res).sendError(HttpServletResponse.SC_OK);<br>        <br>        chain.doFilter(req, res);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>



<p>4.网关配置跨域（用于微服务）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CorsConfiguration</span> &#123;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> CorsWebFilter <span class="hljs-title function_">corsWebFilter</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">UrlBasedCorsConfigurationSource</span> <span class="hljs-variable">source</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">UrlBasedCorsConfigurationSource</span>();<br><br>        <span class="hljs-type">CorsConfiguration</span> <span class="hljs-variable">corsConfiguration</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">CorsConfiguration</span>();<br><br>        <span class="hljs-comment">//1、配置跨域</span><br>        corsConfiguration.addAllowedHeader(<span class="hljs-string">&quot;*&quot;</span>);<br>        corsConfiguration.addAllowedMethod(<span class="hljs-string">&quot;*&quot;</span>);<br>        corsConfiguration.addAllowedOrigin(<span class="hljs-string">&quot;*&quot;</span>);<br>        <span class="hljs-comment">// 是否允许携带cookie跨域</span><br>        corsConfiguration.setAllowCredentials(<span class="hljs-literal">true</span>);<br><br>        source.registerCorsConfiguration(<span class="hljs-string">&quot;/**&quot;</span>,corsConfiguration);<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">CorsWebFilter</span>(source);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>



<h4 id="前端代码实现"><a href="#前端代码实现" class="headerlink" title="前端代码实现"></a>前端代码实现</h4><p>JS采取的是同源策略<br>同源策略是浏览器的一项安全策略，浏览器只允许js 代码请求和当 前所在服务器域名,端口,协议相同的数据接口上的数据,这就是同源 策略.<br>也就是说，当协议、域名、端口任意一个不相同时，都会产生跨域 问题，所以又应该如何解决跨域问题呢</p>
<p><img src="https://raw.githubusercontent.com/hellelixi/note-image01/main/images/image-20230411105517051.png" srcset="/hello_lixi.gitee.io/img/loading.gif" lazyload alt="image-20230411105517051"></p>
<p>前端Vue中使用proxy代理实现跨域</p>
<p>在Vue项目中的vue.config.js文件中，在module.export=defineConfig({    })中添加跨域解决</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-attr">devServer</span>: &#123;<br>	<span class="hljs-attr">proxy</span>: &#123;<br>    	<span class="hljs-string">&#x27;/api&#x27;</span>: &#123;<br>        	<span class="hljs-attr">target</span>: <span class="hljs-string">&#x27;&lt;url&gt;&#x27;</span>, <span class="hljs-comment">//产生跨域的url,只写域名即可，包含了协议，域名，端口（默认）</span><br>            <span class="hljs-attr">changeOrigin</span>: <span class="hljs-literal">true</span> <br>        &#125;<br>    &#125; <br>&#125;<br><span class="hljs-comment">//网络请求/api,则被代理转换成url，变成url+api后的地址，即访问/api/index/index.html，变成</span><br><span class="hljs-attr">http</span>:<span class="hljs-comment">//iwenwili.com/index/index.html</span><br><span class="hljs-comment">//axios中的请求url要去掉域名，变成/api/地址</span><br></code></pre></td></tr></table></figure>

<p>完整vue.config.js代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> &#123; defineConfig &#125; = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;@vue/cli-service&#x27;</span>)<br><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-title function_">defineConfig</span>(&#123;<br>  <span class="hljs-attr">transpileDependencies</span>: <span class="hljs-literal">true</span>,<br>  <span class="hljs-attr">devServer</span>: &#123;<br>	<span class="hljs-attr">proxy</span>: &#123;<br>    	<span class="hljs-string">&#x27;/api&#x27;</span>: &#123;<br>        	<span class="hljs-attr">target</span>: <span class="hljs-string">&#x27;http://iwenwili.com&#x27;</span>, <br>            <span class="hljs-attr">changeOrigin</span>: <span class="hljs-literal">true</span> <br>        &#125;<br>    &#125; <br>  &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>

<p><strong>提示：解决完跨域问题后，要记得重启服务，配置信息才能生效</strong></p>
<p>文章参考内容</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_22136439/article/details/113882168">https://blog.csdn.net/qq_22136439/article/details/113882168</a></p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/hello_lixi.gitee.io/categories/java%E5%BC%80%E5%8F%91/" class="category-chain-item">java开发</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/hello_lixi.gitee.io/tags/%E8%B7%A8%E5%9F%9F/">#跨域</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>跨域处理问题</div>
      <div>https://xistudycode.gitee.io/hello_lixi.gitee.io/2023/04/10/跨域处理/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Mr.LI</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年4月10日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/hello_lixi.gitee.io/2023/04/11/Redis%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" title="Redis学习">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Redis学习</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/hello_lixi.gitee.io/2023/02/14/%E5%AD%A6%E4%B9%A0%E4%BB%BB%E5%8A%A1%E6%80%BB%E7%BB%93/" title="2022.11-2023.1 Java开发学习">
                        <span class="hidden-mobile">2022.11-2023.1 Java开发学习</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>xBolg</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>@Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/hello_lixi.gitee.io/js/events.js" ></script>
<script  src="/hello_lixi.gitee.io/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/hello_lixi.gitee.io/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/hello_lixi.gitee.io/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/hello_lixi.gitee.io/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
